package serveur;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.swing.JOptionPane; 

public class ConnexionBD {
	private static final String drivername = "org.sqlite.JDBC";
    private static final String url = "jdbc:sqlite:Test";
   
    public static Connection connexion = null;

    public static synchronized Connection getInstance() {
        if (connexion == null) {
            try {
                Class.forName(drivername);
                connexion = DriverManager.getConnection(url);
             // mettre en mode de commit manuel
                connexion.setAutoCommit(false);
                
                DatabaseMetaData dbmd = connexion.getMetaData();
                if (dbmd.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE))
                    {
                	connexion.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
                    System.out.println(
                      "Ouverture de la connexion en mode serialisable :\n" +
                      "Estampille " + System.currentTimeMillis() + " " + connexion);
                    }
                else
                    System.out.println(
                      "Ouverture de la connexion en mode read committed (default) :\n" +
                      "Heure " + System.currentTimeMillis() + " " + connexion);
            } catch (ClassNotFoundException cnfe) {
                JOptionPane.showMessageDialog(null, cnfe.getMessage(), "DRIVER INTROUVABLE ! ", JOptionPane.ERROR_MESSAGE);
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
            }
        }
        return connexion;
    }

    /**
     *
     */
    public static void fermer() {
        if (connexion != null) {
            try {
                connexion.close();
                JOptionPane.showMessageDialog(null, "Deconnexion et fermeture de l'application", "FIN DE L'OPERATION", JOptionPane.ERROR_MESSAGE);
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(null, e.getMessage(), "ECHEC DE LA DECONNEXION ", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

}
